<?php
//模块名_控制名
class Product_ProductController extends Zend_Controller_Action
{
	/**
	* 产品列表   
	*
	*/
	private $_s;
	public function preDispatch(){
		$this->_s = new Product_Service_Product();
		$this->tplDirectory = "product/product/";	//控制对应模板目录
	}
	public function viewImgAction(){
		$customer_id = $this->_request->getParam('customer_id','');
		$product_id = $this->_request->getParam('product_id','');
		$pa_path = $this->_request->getParam('pa_path','');
		
		$file = Product_Service_Attached::getPicturePath($customer_id,$pa_path,$product_id);
		
		header('Content-Type: image/jpeg');
		echo $file;
		
	}
	
	public function indexAction(){
		echo Cff::renderTpl($this->tplDirectory.'index.tpl',"layout");
    }
    
    public function listAction(){
    	$intpage = $this->_request->getParam('page',1);
		$pageSize = $this->_request->getParam('pageSize');
		$product_sku = trim($this->_request->getParam('product_sku'));
		$customer_id = trim($this->_request->getParam('customer_id'));
        $product_ref_sku = trim($this->_request->getParam('product_ref_sku'));
		
		$intpage = ($intpage<1)?1:$intpage; 
		$condition=array(
            'product_ref_sku'=>$product_ref_sku,
			'product_sku'=>$product_sku,
			'customer_id'=>$customer_id,
		);
		$count=$this->_s->getByCondition($condition,'count(*)','',0,0);
		$data=array(
			'count'=>0,
			'ask'=>0
			);
		if($count>0){
			$Rows=$this->_s->getByCondition($condition,'*','product_id',$pageSize,$intpage);
			foreach($Rows as $key => $value){
					
				$Rows[$key]['product_title'] = empty($value['product_title_cn'])?$value['product_title']:$value['product_title_cn'];
				$Rows[$key]['product_packect_type'] = $this->_s->getPackageNameByProductId($value['product_id']);				

				$Rows[$key]['product_status']=Product_Service_Product::getProductStatus($value['product_status']);
				$Rows[$key]['product_warehouse_status']=Product_Service_Product::getWarehouseStatus($value['product_warehouse_status']);
					
				$product_option_choose = $this->_s->getProductCategory($value['product_id']);
				$Rows[$key]['product_category']= $product_option_choose['poc_value'];
							
				$Rows[$key]['wp'] = array();
				$Rows[$key]['has_wpb'] = 0;
				$wps = Warehouse_Service_Products::getByAllProductId($value['product_id']);
// 				print_r($wps);exit;
				if($wps){					
					foreach($wps as $k=>$wp){
						$con = array('product_id'=>$value['product_id'],'ws_code'=>$wp['ws_code'],'warehouse_id'=>$wp['warehouse_id']);
						$wpbs = Warehouse_Service_ProductsBatch::getByCondition($con);
// 						print_r($wpbs);
						$wps[$k]['wpb'] = $wpbs;
						
						$Rows[$key]['has_wpb'] = 0;						
					}
					$Rows[$key]['wp'] = $wps;
					$Rows[$key]['has_wpb'] = 1;
				}
			}
// 			print_r($Rows);exit;
			$data=array(
				'count'=>$count,
				'result'=>$Rows,
				'ask'=>1
			);
		}
		die(Zend_Json::encode($data));
    }
	
	public function viewPictureAction(){
		$productId = $this->_request->id;
		$url = Product_Service_Receiving::getPicture($productId);
		header("content-type:image/jpeg");
		if($url !== false){
			echo file_get_contents($url);
		}else{
			echo file_get_contents("images/noimg.jpg");
		}
	}
	
	public function viewQcPictureAction(){
		$paid = $this->_request->paid;
		$url = Product_Service_Receiving::getQcPicture($paid);
		header("content-type:image/jpeg");
		if($url !== false){
			echo file_get_contents($url);
		}else{
			echo file_get_contents("images/noimg.jpg");
		}
	}
	
	public function singleAction(){
		$product_id = $this->_request->getParam('product_id');
		
		$product = $this->_s->getByProductId($product_id);
		$data=array(
			'result'=>'产品非法',
			'ask'=>0
		);
		if($product){
			$productOptions = $this->_s->getProductOptions($product_id);
			
			if($product['product_warehouse_status']==1){
				$data['result'] = "已经收过货，不能修改";
			}else{
				$data=array(
					'result'=>$product,
					'options'=>$productOptions,
					'ask'=>1
				);
			}
//			print_r($productOptions);
			
		}
		
		die(Zend_Json::encode($data));
	}
    
    
	public function optionAction(){			
			$productOptions = $this->_s->getProductOptions();
			$data=array(
				'options'=>$productOptions,
				'ask'=>1
			);		
		
		die(Zend_Json::encode($data));
	}
    
	public function packageAction(){	
		$product_id = $this->_request->getParam('product_id');		
		$packages = $this->_s->getPackageByProductId($product_id);
//		exit;
		$packageMaps = $this->_s->getPackageMapByProductId($product_id);
//		$packageMaps = $this->_s->getPackageMapByProductId("136");
//		print_r($packageMaps);die();
		$data=array(
			'warehouse'=>$packages,
			'packageMap'=>$packageMaps,
			'ask'=>1
		);		
		
		die(Zend_Json::encode($data));
	}
	public function packageMapSaveAction(){	
		$product_id = $this->_request->getParam('product_id');	
		$warehouseid = $this->_request->getParam('warehouseid');
		$packageid = $this->_request->getParam('packageid');	
		$ppm_id = $this->_request->getParam('ppm_id');
		$row = array(
			"product_id"=>$product_id,
			"warehouse_id"=>$warehouseid,
			"package_id"=>$packageid,
		);
		$model_packageMap = new Product_Model_PackageMap();
		if($ppm_id){
			$flag = $model_packageMap->update($row,$ppm_id);
		}else{
			$flag = $model_packageMap->add($row);
			
		}	
//		print_r($packageMaps);die();
		if($flag==false){
			$data=array(
				'ask'=>0
			);			
		}else{
			$data=array(
				'ask'=>1
			);		
		
		}
		
		die(Zend_Json::encode($data));
	}
    
    public function baseinfoAction(){
		$product_id = $this->_request->getParam('product_id');
		
		$product = $this->_s->getProductInfo($product_id);
		$selectOptions = $this->_s->getSelectOptions();
		
		$return = array(
			"ask" => 0,
		);
		if($product !== false){//找到产品
			
			$return = array(
				"ask" => 1,
				"result" => array(
					"product" => $product,
				),
			);
		}
		die(json_encode($return));
	}
	
	/**
	 * 更新product状态 激活 删除 草稿
	 * */
    public function updateStatusAction(){
		$product_id = $this->_request->getParam('product_id');
		$product_status = $this->_request->getParam('product_status');
//		$product = $this->_s->getByProductId($product_id);
		$data=array(
			'ask'=>0,
		);
		$arr['product_status'] = $product_status;	
		$product_id = preg_replace("/(.*),$/","\\1",$product_id);	
		$product_ids = explode(",",$product_id);	
//		print_r($product_ids);die();
		if($product_ids){
			$arr = array();
			switch($product_status){
				case 0:					
					$msg = $this->_s->delete($product_ids);	
					break;
				case 1:
					$msg = $this->_s->activate($product_ids);	
					
					break;
				case 2:
					$msg = $this->_s->inactivate($product_ids);
					break;
				default :
					$msg = 'error';
				
			}
			if(is_array($msg)){
				$msg = implode("<br/>",$msg);				
			}
			$data=array(
				'ask'=>1,
				'msg'=>$msg,
			);		
		}
		die(Zend_Json::encode($data));
	}
	
	public function updateAction(){
		$serviceObj = new Product_Service_Product();
		$params = $this->_request->getParams();
		
		$productOptionValues = array();		
		$po_selects = $this->_request->getParam("po_select","");
		if($po_selects){		
		
			foreach($po_selects as $k=>$v){
				$productOptionValue = array(
						"po_id" => $k,
						"poc_id" => $v,
						"po_value" => ''
					);	
				$productOptionValues[] = $productOptionValue;		
			}
		}
		$po_inputs = $this->_request->getParam("po_input","");
		if($po_inputs){		
			foreach($po_inputs as $k=>$v){
				$productOptionValue = array(
						"po_id" => $k,
						"poc_id" => 0,
						"po_value" => $v
					);	
				$productOptionValues[] = $productOptionValue;		
			}	
		}
		$row = array(
			// $productCategory = trim($this->_request->getParam("productCategory","");//产品种类
			"product_title" => trim($this->_request->getParam("product_name","")),//产品名称
			"product_sku" => trim($this->_request->getParam("product_sku","")),//产品编号
			"product_net_weight" => trim($this->_request->getParam("product_net_weight","")),//产品净重
			"product_weight" => trim($this->_request->getParam("product_weight","")),//产品重量
			"product_length" => trim($this->_request->getParam("product_length","")),//产品长
			"product_width" => trim($this->_request->getParam("product_width","")),//宽
			"product_height" => trim($this->_request->getParam("product_height","")),//高
			"product_declared_value" => trim($this->_request->getParam("product_price","")),//申报价值
			"customer_id" => trim($this->_request->getParam("customer_id","")),//客户ID
			// $declareName = trim($this->_request->getParam("declareName",""));//申报品名
		);
		
		$product_id = $this->_request->getParam('product_id');
		if($product_id){
			$edit = $serviceObj->edit($row,$product_id,$productOptionValues);	
			$op = "Update";		
		}else{
			$edit = $serviceObj->create($row,$productOptionValues);		
			$op = "Create";			
			
		}
		if($edit === true){//更新成功
				// $this->view->message = I18n::getInstance()->translate("0000015");
				$return = array(
					"ask" => 1,
					"result" => "$op successful",
				);
			}else if($edit === false){//更新失败
					$return = array(
						"ask" => 0,
						"result" => array(
							"productOptionValues" => $productOptionValues,
							"row" => $row,
							"message" => "Update failure",
						),
					);
			}else if(is_array($edit)){
				$return = array(
						"ask" => 0,
						"result" => array(
							"productOptionValues" => $productOptionValues,
							"row" => $row,
							"message" => implode("<br/>",$edit),
						),
					);
			}
		die(Zend_Json::encode($return));
	}
	
	//打印
	public function printLabelAction(){
		$params = $this->_request->getParams();
		$printType=$this->_request->getParam('type','5x2');
		$rows = array();
		foreach($params as $key => $param){
			if(strpos($key,"count") !== false){
				$rows[substr($key,strpos($key,"count")+5)] = $param;
			}
		}
		if($printType=="5x2"){
			$results = $this->_s->getPrintLabelInfo($rows);
	// 		print_r($results);
	// 		print_r($rows);die();
			$this->view->results = $results;		
			echo Cff::renderTpl($this->tplDirectory.'print.tpl',"print");
		}else{
			$results = $this->_s->getPrintLabelInfo($rows);
			$results = array_chunk($results,3);
			$this->view->resultsAll = $results;
			echo Cff::renderTpl($this->tplDirectory.'print_new.tpl',"print");
			
		}
		
	}
	/*
	 * 条形码
	 */
	public function barcodeAction(){
		Product_Service_Barcode::barcode($this->_request->code);
	}
	/*
	 * 文件上传
	 */
	public function uploadFileAction(){
//		$service_upload = new Product_Service_Upload();
//		$arr = $service_upload->readEXCEL($_FILES['productFile']['tmp_name']);
		$arr = $this->_s->readUploadFile($_FILES['productFile']['name'],$_FILES['productFile']['tmp_name']);
		if(is_array($arr)){
			$this->view->products=$arr;		
			$this->view->err = "";	
		}else{
			$this->view->err = "文件格式不正确或者内容为空";
		}
//		print_r($arr);
//		$fileName = $_FILES['productFile']['name'];
//		$filePath = $_FILES['productFile']['tmp_name'];
//		$fileData = $serviceObj->readUploadFile($fileName,$filePath);
		echo Cff::renderTpl($this->tplDirectory.'batchAdd.tpl',"layout");
	}
    
	/*
	 * 批量添加
	 */
	public function batchAddAction(){
		$params = $this->_request->getParams();
		
//		print_r($params);
		
		$arr = array();
		
		foreach($params as $k=>$v){
			if(is_array($v)){
				foreach($v as $k1=>$v1){
					$arr[$k1][$k] = $v1;
				}
			}
		}
		
		$message = "";
		foreach($arr as $v){
			$row = array(
				// $productCategory = trim($this->_request->getParam("productCategory","");//产品种类
				"product_title" => trim($v['SKUName']),//产品名称
				"product_sku" => trim($v['SKUNo']),//产品编号
				"product_weight" => trim($v['product_weight']),//产品重量
				"product_length" => trim($v['product_length']),//产品长
				"product_width" => trim($v['product_width']),//宽
				"product_height" => trim($v['product_height']),//高
				"product_declared_value" => trim($v['product_declared_value']),//申报价值
				"customer_id" => trim($v['customer_id']),//客户ID
				// $declareName = trim($this->_request->getParam("declareName",""));//申报品名
			);
			$productOptionValues = array();		
			$po_selects = $v['Category'];
			if($po_selects){	
				$model_productOptionChoose = new Product_Model_ProductOptionChoose();	
				$pocValue = $model_productOptionChoose->getByPocValue($po_selects)->toArray();	
					
				$productOptionValue = array(
						"po_id" => $pocValue['po_id'],
						"poc_id" => $pocValue['poc_id'],
						"po_value" => ''
					);	
				$productOptionValues[] = $productOptionValue;		
				
			}
			$po_inputs = $v['Min_Qty'];
			if($po_inputs){		
				$model_productOption = new Product_Model_ProductOptions();			
				$option = $model_productOption->getByName("Min Qty")->toArray();
				$productOptionValue = array(
						"po_id" => $option['po_id'],
						"poc_id" => 0,
						"po_value" => $po_inputs
					);	
				$productOptionValues[] = $productOptionValue;		
				
			}			
			 $result = $this->_s->create($row,$productOptionValues);	
//			 print_r($result);	
			 if($result === true){//更新成功
				// $this->view->message = I18n::getInstance()->translate("0000015");				
				$message .= $v['SKUName']." 结果： create successful<br/>";				
			}else if(is_array($result)){
				$message .= $v['SKUName']." 结果：".implode("----",$result)."<br/>";
			}
		}
		$data = array("ask"=>1,"msg"=>$message);
//		print_r($arr);
		
		die(Zend_Json::encode($data));		
	}
    
    
	public function uploadPictureAction(){
		$tempFile = $_FILES['Filedata']['tmp_name'];
		$serviceObj = new Product_Service_Product();
	
		$targetDir = $serviceObj->getPictureUploadDir();
		$targetFile =  $targetDir ."./". $_FILES['Filedata']['name'];

		$bool = @move_uploaded_file($tempFile,$targetFile);
		if($bool){
			$arr = array(
				"ask"=>1,
				"filepath"=>"/product/product/view-image/fileName/".$_FILES['Filedata']['name']
			);
		}else{
			$arr = array(
				"ask"=>0,
				"err"=>$_FILES['Filedata']['name']."  can't be saved'"
			);
		}
		
		echo json_encode($arr);
		exit;
	}
	
// 	查看图片
	public function viewImageAction(){
		$customer = Customer_Service_Customer::getByCustomerId("A0317");
		$customerId = $this->_request->getParam("customer_id",'');
		$productId = $this->_request->getParam("product_id","");
		$fileName = $this->_request->fileName;
		
		$serviceObj = new Product_Service_Product();		
		$targetDir = $serviceObj->getPictureUploadDir();		
		header('Content-Type: image/jpeg');
		
		$filepath = $targetDir ."";
		if($customerId){
			$filepath.="/"."$customerId";
			echo file_get_contents("../public/images/noimg.jpg");exit;
		}
		
		if($productId){
			$filepath.="/"."$productId";
		}
		if($fileName){
			$filepath.="/"."$fileName";
			echo file_get_contents("../public/images/noimg.jpg");exit;
		}
		if(file_exists($filepath)){
			echo file_get_contents($filepath);
		}else{
			echo file_get_contents("../public/images/noimg.jpg");
				
		}
		exit;
	}
	
	/**
	 *  查看产品信息
	 */
	public function viewProductInfoAction(){
		$serviceObj = new Product_Service_Product();
		$productId = $this->_request->productId;
		
		$res = $serviceObj->getProductInfo($productId);
		$edit = $this->_request->edit;
		$qcset = $this->_request->qcset;
		
		$this->view->customerId = $res["customer_id"];
		$this->view->productId = $productId;
		$this->view->edit = $edit;
		$this->view->qcset = $qcset;
		$this->view->product_is_qc = $res['product_is_qc'];
		
		echo $this->view->render($this->tplDirectory."product-info.tpl");
	}
	
	public function getQuanlityControlAction(){
		$serviceObj = new Product_Service_Product();
		$povServiceObj = new Product_Service_ProductOptionValue();
		
		$p_id = $this->_request->getParam("productId",'');
		$selectOptions = $serviceObj->getSelectOptions();
		
		$objConfig = new Default_Model_Config();
		$congifRes = $objConfig->getByValue('QUANTITY_CONTROL_ID');
		$return = array();
		foreach($selectOptions as $key=>$val){
			if($val['id']!= $congifRes['config_value']) unset($selectOptions[$key]);
			else{ 
				foreach( $val['options'] as $v ) { 
					$res = $povServiceObj->getByCondition($p_id,$v['po_id'],$v['poc_id']);
					$v['po_value']= $res ? $res[0]['po_value'] : '';
					$return[]=$v;
				}
			}
		}
		die(json_encode($return));
	}
	
	public function quanlityControlEditAction(){
		 $povServiceObj = new Product_Service_ProductOptionValue();
		 $params = $this->_request->getParams();
		 $p_id = $params['productId'];
		 $po_id = $params['poid'];
		 $poc_ids = $this->_request->getParam('pocid','');
		 $op_values = $params['opvalue'];
		 $now = date("Y-m-d H:i:s");
		 //修改的要保存  之前没勾选现勾选需要增添 之前勾选但现没勾选的要删除
		 $poc_id_str = array();
		 $flag = true;
		 if(!empty($poc_ids)){
			 foreach ($poc_ids as $key=>$poc_id){
				 $poc_id_str[]= $poc_id ;
				 $res = $povServiceObj->getByCondition($p_id,$po_id,$poc_id);
				 if($res){
					 if(!$povServiceObj->modifyByCondition(array('po_value'=>$op_values[$key],'pov_add_time'=>$now),$p_id,$po_id,$poc_id)){$flag=false;}
				 }else{
					 if($op_values[$key]!=''){
					 	if(!$povServiceObj->add(array('product_id'=>$p_id,'po_id'=>$po_id,'poc_id'=>$poc_id,'po_value'=>$op_values[$key],'pov_add_time'=>$now))){ $flag = false;}
					 }
				 }
			 }
		 }
		 //'delete from product_option_value where product_id=1 and po_id=4 and poc_id not in(1,2,3)';
		 $povServiceObj->deleteByCondition($p_id,$po_id,$poc_id_str);
		 $return = array('ask'=>$flag,'result'=>'Success');
		 die(json_encode($return));
	}	
	
	
	public function editAction(){
		$serviceObj = new Product_Service_Product();
		$params = $this->_request->getParams();
		$productOptionValues = array();
		foreach($params as $key => $value){
			if(strpos($key,"autoGenerate_") !== false){
				$keyArr = explode("_",$key);//keyArr[1] 为po_id
				$productOptionValue = array(
					"po_id" => $keyArr[1],
					"poc_id" => $value
				);
				$productOptionValues[$keyArr[1]] = $productOptionValue;
			}
		}
//		print_r($productOptionValues);die();
		$row = array(
			// $productCategory = trim($this->_request->getParam("productCategory","");//产品种类
			"product_title" => trim($this->_request->getParam("productName","")),//产品名称
			"product_title_cn" => trim($this->_request->getParam("productCname","")),//产品中文名称
			"product_sku" => trim($this->_request->getParam("productNumber","")),//产品编号
			"product_pack_unit" => trim($this->_request->getParam("productFlat","")),//产品单位
			"product_weight" => trim($this->_request->getParam("weight","")),//产品重量
			"product_length" => trim($this->_request->getParam("lenght","0.00")),//产品长
			"product_width" => trim($this->_request->getParam("width","0.00")),//宽
			"product_height" => trim($this->_request->getParam("height","0.00")),//高
			"product_declared_value" => trim($this->_request->getParam("declareWorth","")),//申报价值
			"product_is_qc" => trim($this->_request->getParam("product_isqc",0)),//是否质检
			// $declareName = trim($this->_request->getParam("declareName",""));//申报品名
		);
		$pictures = $this->_request->getParam("picture",array());
		$links = $this->_request->getParam("link",array());
		$edit = $serviceObj->updateInfo($params['productId'],$row,$productOptionValues,$pictures,$links);
		if($edit === true){//更新成功
			// $this->view->message = I18n::getInstance()->translate("0000015");
			$return = array(
				"ask" => true,
				"result" => "Update successful",
			);
		}else if($edit === false){//更新失败
				$return = array(
					"ask" => false,
					"result" => array(
						"productOptionValues" => $productOptionValues,
						"row" => $row,
						"pictures" => $pictures,
						"message" => "Update failure",
					),
				);
		}else if(is_array($edit)){
			$return = array(
					"ask" => false,
					"result" => array(
						"productOptionValues" => $productOptionValues,
						"row" => $row,
						"pictures" => $pictures,
						"errors" => $edit,
					),
				);
		}
		die(json_encode($return));
	}
	
	public function updateQtyAction(){
		$serviceObj = new Product_Service_Product();
		$params = $this->_request->getParams();
		$productOptionValues = array();
		foreach($params as $key => $value){
			if(strpos($key,"autoGenerate_") !== false){
				$keyArr = explode("_",$key);//keyArr[1] 为po_id
				$productOptionValue = array(
					"po_id" => $keyArr[1],
					"poc_id" => $value
				);
				$productOptionValues[$keyArr[1]] = $productOptionValue;
			}
		}
		$pictures = $this->_request->getParam("picture",array());
		$links = $this->_request->getParam("link",array());
		$edit = $serviceObj->updateQty($params['productId'],$productOptionValues,$pictures,$links);
		if($edit === true){//更新成功
			// $this->view->message = I18n::getInstance()->translate("0000015");
			$return = array(
				"ask" => true,
				"result" => "Update successful",
			);
		}else if($edit === false){//更新失败
				$return = array(
					"ask" => false,
					"result" => array(
						"productOptionValues" => $productOptionValues,
						"pictures" => $pictures,
						"message" => "Update failure",
					),
				);
		}else if(is_array($edit)){
			$return = array(
					"ask" => false,
					"result" => array(
						"productOptionValues" => $productOptionValues,
						"pictures" => $pictures,
						"errors" => $edit,
					),
				);
		}
		die(json_encode($return));
	}
	
	public function getProductLogAction(){
		$serviceObj = Product_Service_Product::getInstance();
		$page = $this->_request->getParam("page",1);
		$pageSize = $this->_request->getParam("pageSize",20);
		$productId = $this->_request->getParam("productId");
		$logs = $serviceObj->getLog($productId,$page,$pageSize);
		$logCount = $serviceObj->getLogCount($productId);
		$return = array(
			"ask" => true,
			"result" => array(
				"logs" => $logs,
				"total" => $logCount,
			)
		);
		die(json_encode($return));
	}
	
	public function getProductPicturesAction(){
		$productId = $this->_request->productId;
		$serviceObj = Product_Service_Product::getInstance();
		$pictures = $serviceObj->getAllProductPicture($productId);
		$return = array(
				"ask" => true,
				"result" => array(
					"pictures" => $pictures,
				)
			);
		die(json_encode($return));
	}
	
	public function getOrdersAction(){	//与产品相关的订单	
		$page = $this->_request->getParam("page",1);
		$pageSize = $this->_request->getParam("pageSize",20);
		$productId = $this->_request->getParam("productId");
		
		$condition = array("product_id"=>$productId);
		$logs = Order_Service_OrderProduct::getByCondition($condition,'*',"",$page,$pageSize,false);
		$logCount = Order_Service_OrderProduct::getByCondition($condition,'count(*)');
		foreach($logs as $k=>$v){
			$order = Order_Service_Order::getByValue($v['orders_code'],"orders_code");
			$logs[$k]['order_status'] = Order_Service_Order::getOrderStatus($order['orders_status']);
			$logs[$k]['add_time'] = $order['add_time'];
		}
		$return = array(
			"ask" => true,
			"result" => array(
				"logs" => $logs,
				"total" => $logCount,
			)
		);
		die(json_encode($return));
	}
	
	public function shelfLogAction(){
		$productId = $this->_request->productId;
		$page = $this->_request->getParam("page",0);
		$pageSize = $this->_request->getParam("pageSize",20);
		$tmpcond=array('product_id'=>$productId);
		$totalResult = Product_Service_ProductStocket::getByCondition($tmpcond,'count(*)','ps_last_update',0,0);
		$results=Product_Service_ProductStocket::getByCondition($tmpcond,'*','ps_last_update',$pageSize, $page);
		$return = array("ask" => false);
		if(!empty($results)){
			$return['ask'] = true;
			$return['results'] = $results;
		}
		$return['total'] = count($totalResult);
		die(json_encode($return));
	}
	
	/**
	 *  总库存日志
	 * 
	 */
	
	public function getPorductStocketLogAction(){
			$productId = $this->_request->productId;
			$page = $this->_request->getParam("page",0);
			$pageSize = $this->_request->getParam("pageSize",20);
			$tmpcond=array('product_id'=>$productId);
			
			
			
			$totalResult = Product_Service_ProductStocketLog::getByCondition($tmpcond,'count(*)','psl_add_time',0,0);
			$results=Product_Service_ProductStocketLog::getByCondition($tmpcond,'*','psl_add_time',$pageSize, $page);
			$return = array("ask" => false);
			$data=array();
			if(!empty($results)){
				
				foreach ($results as $val){
					if($val['user_id']>0){
						$operNameRow=User_Service_User::getByUserId($val['user_id']);
						$operName=$operNameRow['name'];
						$val['user_id']=$operName;
					}else if($val['user_id']==0){
						$val['user_id']='系统';
					}
					$data[]=$val;
					
					
				}
				
				
				$return['ask'] = true;
				$return['results'] = $data;
			}
			$return['total'] = count($totalResult);
			die(json_encode($return));
	}
	
	
	/**
	 *  获取产品信息
	 */
	public function getProductInfoAction(){
		$productId = $this->_request->productId;
		$serviceObj = Product_Service_Product::getInstance();
		$product = $serviceObj->getProductInfo($productId);
		$selectOptions = $serviceObj->getSelectOptions();
		if($product === false){//没有找到产品
			$output = array(
				"ask" => false,
				"result" => "No result",
			);
			die(json_encode($output));
		}
		$this->view->productId = $productId;
		$product['product_status'] = $serviceObj->getStatusText($product['product_status']);

		$output = array(
			"ask" => true,
			"result" => array(
				"product" => $product,
				"customerId" => $product["customer_id"]
			)
		);
		die(json_encode($output));
	}
	
	
	public function baseinfosAction(){
		$productId = $this->_request->productId;
		$serviceObj =  new Product_Service_Product();
		$product = $serviceObj->getProductInfo($productId);	
		$selectOptions = $serviceObj->getSelectOptions();

		$servicePicObj = Product_Service_Product::getInstance();
		
		if($product !== false){//找到产品
			//查找产品图片
			//判断产品库存
			$ProductStocket = Product_Service_ProductStocket::getByProductId($product['product_id']);
			$product['ps_quantity'] = 0;
			if($ProductStocket){
				$product['ps_quantity'] = $ProductStocket['ps_quantity']+$ProductStocket['ps_quantity_hold'];				
			}				
			$pictures = $servicePicObj->getAllProductPicture($productId);

			$links = $serviceObj->getProductLinks($productId);
			$return = array(
				"ask" => true,
				"result" => array(
					"product" => $product,
					"pictures" => $pictures,
					"links" => $links,
					"selectOptions" => $selectOptions,
				),
			);
			die(json_encode($return));
		}
	}
	
//	public function uploadPictureAction(){
//		$tempFile = $_FILES['picture']['tmp_name'];
//		
//		//获得图片存储的临时位置
//		$serviceObj = new product_Service_Product();
//		$str = var_export($tempFile,true);
//		self::logError($str);		 
//		
//		$targetDir = $serviceObj->getPictureUploadDir($this->_request->customerId);
//		$targetFile =  $targetDir ."/". $_FILES['picture']['name'];
//		
////		$filename = md5($_FILES['picture']['name']."".time())."".preg_replace("/[^\.]*(\.[a-zA-Z]+$)/","\\1",$_FILES['picture']['name']);
////		$targetFile =  $targetDir ."/".$filename;
//		$arr = array("ask"=>0);
//		if(move_uploaded_file($tempFile,$targetFile)){
//			$arr = array("ask"=>1,"filepath"=>1);
//			$row = array('product_id'=>0,"pa_path"=>$targetFile,
//				"pa_file_type"=>"img","pa_status"=>0,"languages_id"=>1,
//				"pa_sort"=>1,"pa_last_update"=>date('Y-m-d H:i:s'));
//			$id = product_Service_ProductAttached::add($row);
//			
//			$arr = array("ask"=>1,
//				"picid"=>"p_".$id,
//				"filepath"=>"/product/product/view-image/fileName/".$_FILES['picture']['name'],
//				);
//			
//		}else{
//			$arr = array("ask"=>0,"error"=>'Inner Error');
//		}
//		echo json_encode($arr);
//		exit;
//	}
	
	public static function logError($error){
    	$logger = new Zend_Log();
		$uploadDir = '/var/www/CFF/admin/data/log/test.log';
		$writer = new Zend_Log_Writer_Stream($uploadDir.'shipRate4.log');
		$logger->addWriter($writer);
		$logger->info(date('Y-m-d H:i:s').': '.$error." \n");
    }
    
    public function asnLogAction(){
    	$productId = $this->_request->productId;
    	$page = $this->_request->getParam("page",0);
		$pageSize = $this->_request->getParam("pageSize",20);
		
    	$data=array('ask'=>0);
    	$rows = $cond = array();
    	$cond['product_id'] = $productId;
    	
    	$receivingItems = Product_Service_ReceivingItem::getByCondition($cond,'*',$page, $pageSize);
    	$total = Product_Service_ReceivingItem::getByCondition($cond,'count(*)');
    	foreach ($receivingItems as $key => $val){
    		$rows[$key]['receiving_code'] = $val['receiving_code'];
    		$rows[$key]['received_qty'] = $val['received_qty'];
    		$rows[$key]['created'] = $val['created'];
    		
    		$receiving = Product_Service_Receiving::getByValue($val['receiving_code'],'receiving_code');
    		if($receiving['status'] == 0 || $receiving['status'] == 1){
    			$rows[$key]['status'] = '未收货';
    		}elseif ($receiving['status'] == 2){
    			$rows[$key]['status'] = '收货中';
    		}elseif ($receiving['status'] == 3){
    			$rows[$key]['status'] = '已收货';
    		}else {
    			$rows[$key]['status'] = '';
    		}
    		
    	}
    	if(!empty($rows)){
    		$data['ask'] = 1;
    		$data['result']['logs'] = $rows;
    		$data['result']['total'] = $total;
    	}
    	
    	die(Zend_Json::encode($data));
    }

    /*
    * 获取当前产品货架信息
    */
    public function getShelfProductAction(){
        $productIds = $this->_request->checkPoduct;
        $proServiceObj = new Product_Service_Product();
        $result=array('ask'=>0,'result'=>array());
        $products = array();
        $i=0;
        if(!empty($productIds)){
            foreach($productIds as $key => $val){
                $warehouseProductRows = Warehouse_Service_Products::getByCond(array('product_id'=>$val,'warehouse_id'=>1),'*');
                if (!empty($warehouseProductRows)) {
                    foreach($warehouseProductRows as $wpkey => $wpval){
                        if($wpval['wp_status']!=0){
                            $product = Product_Service_Product::getByProductId($wpval['product_id']);
                            if($product['product_ref_sku']=="YES"){//共卖 无需打印标签  跳过
                                continue;
                            }
                            $i++;
                            $productInfo = $proServiceObj->getProductInfo($wpval['product_id']);
                            $products[$i]['ws_code'] = $wpval['ws_code'];
                            $products[$i]['customer_id'] = $productInfo['customer_id'];
                            $products[$i]['product_id'] = $productInfo['product_id'];
                            $products[$i]['product_sku'] = $productInfo['product_sku'];
                            //$products[$i]['product_title'] = $productInfo['product_title'];
                            $products[$i]['category'] = $productInfo['category']['poc_value'];
                            $products[$i]['quantity'] = $wpval['wp_quantity'] + $wpval['wp_quantity_hold'] ;
                        }
                    }
                }
            }
        }
        $result=array('ask'=>count($products)>0?1:0,'result'=>$products);
        die(json_encode($result));
    }
}